//
//  XJSQLiteManager.swift
//  新浪微博
//
//  Created by 徐绩 on 16/5/3.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit

private let DB_NAME = "status.db"

class XJSQLiteManager: NSObject {

    static let sharedManager = XJSQLiteManager()
    
    var queue: FMDatabaseQueue!
    
    override init() {
        
        super.init()
        
        //数据库路径
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent(DB_NAME)
        
        print(path)
        
        //打开数据库
        queue = FMDatabaseQueue(path: path)
        
        //建表
        createTabel()
        
    }
    /**
     创建表
     */
    private func createTabel(){
    
        let sqlPath = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil)!
        
        //读取sql语句
        let sql = (try! NSString(contentsOfFile: sqlPath, encoding: NSUTF8StringEncoding)) as String
        
        //建表
        queue.inDatabase { (db) -> Void in
            if db.executeUpdate(sql, withArgumentsInArray: nil){
            
                print("建表成功")
            }else{
                print("建表失败")

            }
        }
    }
    
    /**
     从数据库查数据

     */
    func execRecordSet(sql: String) -> [[String: AnyObject]]{
    
        var result = [[String: AnyObject]]()
        
        XJSQLiteManager.sharedManager.queue.inDatabase { (db) -> Void in
            
            let res = db.executeQuery(sql, withArgumentsInArray: nil)
            
            //查询是否有下一条语句
            while res.next(){
            
                var dict = [String: AnyObject]()
                // 把数据的内容封装成字典
                for i in 0..<res.columnCount(){
                
                    let key = res.columnNameForIndex(i)
                    let value = res.objectForColumnIndex(i)
                    
                    dict[key] = value
                    
                }
                result.append(dict)
            }
        }
        return result
    }
    
    
    
    
    
    
    
    
}
